<template>
  <base-container :footer="isActivated" footer-height="85px" is-template :show-title="false">
    <base-container>
      <QueryFieldsHJBW
        ref="QueryFieldsRef"
        v-model:type="type"
        v-model:bw="BwFormFields"
        v-model:cibao="CiBaoFormFields"
        v-model:get-result="getResult"
        v-model:HjbwFormFields="HJBWFormFields"
        :package-list="packageList"
        :submitting="loading"
        :bw-submitting="bwSearching"
        :LandingPageList="LandingPageList"
        :combo-price-list="comboPriceList"
        :combo-price-loading="comboPriceLoading"
        :code="route.name as string"
        @cibao-submit="loadKeywordList"
        @hjbw-submit="hjbwLoadKeywordList"
        @cibao-reset="handleCiBaoReset"
        @cibao-package-change="handlePackageChange"
        @bw-submit="handleBwSearcher"
        @bw-reset="handleBwReset"
      />
      <div v-show="CiBao || CBYXB">
        <Divider />
        <table-toolbar>
          <span class="ml-2">推广区域：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal"> 全国 </a-tag>
          <span class="ml-2">最快开始投放时间：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ releaseRange }}
          </a-tag>
          <template #bar-left>
            <div>
              <span class="font-bold ft-16">推广关键词</span>
              <ForbiddenText :category="type" />
            </div>
          </template>
        </table-toolbar>
        <a-row :gutter="16">
          <a-col :span="12">
            <KeywordTable
              :loading="keywordLoading"
              :max-length="currentPackage?.wordsNumTotal ?? 0"
              v-model:keyword-table-data="keywordTableData"
              v-model:selected-table-data="selectedTableData"
            />
          </a-col>
          <a-col :span="12">
            <SelectedTable
              v-model:raw-keyword-table-data="rawKeywordTableData"
              v-model:selected-table-data="selectedTableData"
            />
          </a-col>
        </a-row>
        <!--<a-alert type="success" class="mt-5">
          <template #message>   
            1.近日百度流量接口出现不稳定情况，导致前端查价出现报错或者不出现推荐关键词的情况，技术已经紧急处理，预计2-3个工作日；<br />
            2.遇到此种情况可以尝试多次点击“查询”触发接口，一般3-5次可以出查询结果。给您带来的不便还请谅解。
          </template>
        </a-alert>-->
      </div>
      <div v-show="HJBW">
        <Divider />
        <div style="display: flex">
          <a-form-item label="是否黄金展位转移" name="hzTransferCode" style="margin-top: 10px">
            <a-radio-group v-model:value="HJBWFormFields.hzTransferCode">
              <a-radio-button :value="1">是</a-radio-button>
              <!-- <a-radio-button :value="2">否</a-radio-button> -->
            </a-radio-group>
          </a-form-item>
          <a-form-item
            v-if="HJBWFormFields.hzTransferCode === IsFromHjzwEnum.Yes"
            label="转移备注"
            name="hzNotes"
            style="margin-top: 10px; margin-left: 20px"
          >
            <a-textarea
              style="width: 300px"
              :rows="1"
              v-model:value.trim="HJBWFormFields.hzNotes"
              placeholder="请输入转移公司名称！"
              allow-clear
            />
          </a-form-item>
        </div>
        <table-toolbar>
          <span class="ml-2">推广时长：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ HJBWFormFields.comboPriceName }}
          </a-tag>
          <span class="ml-2">投放时段：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal"> {{ HJBWFormFields.onLinePeriod }} </a-tag>
          <span class="ml-2">最快开始投放时间：</span>
          <a-tag color="red" class="toolbar-local mb-0 mr-0 leading-normal">
            {{ releaseRange }}
          </a-tag>
          <template #bar-left>
            <div>
              <span class="font-bold ft-16">推广关键词</span>
              <ForbiddenText :category="type" />
              <span>（单个关键词长度至少4个字8个字符，一个汉字算两个字符，英文字母算一个字符）</span>
            </div>
          </template>
        </table-toolbar>
        <a-row :gutter="16">
          <a-col :span="12">
            <KeywordTable
              :loading="hjbwKeywordLoading"
              v-model:keyword-table-data="hjbwKeywordTableData"
              v-model:selected-table-data="hjbwSelectedTableData"
            />
            <!-- :max-length="currentPackage?.wordsNumTotal ?? 0" -->
          </a-col>
          <a-col :span="12">
            <SelectedTable
              v-model:raw-keyword-table-data="rawKeywordTableDataHjbw"
              v-model:selected-table-data="hjbwSelectedTableData"
              :msiusidppoi="0"
            />
          </a-col>
        </a-row>
        <!--<a-alert type="success" class="mt-5">
          <template #message>
            1.近日百度流量接口出现不稳定情况，导致前端查价出现报错或者不出现推荐关键词的情况，技术已经紧急处理，预计2-3个工作日；<br />
            2.遇到此种情况可以尝试多次点击“查询”触发接口，一般3-5次可以出查询结果。给您带来的不便还请谅解。
          </template>
        </a-alert>-->
      </div>
    </base-container>

    <div v-show="(getResult && BW) || BWYXB">
      <BaseContainer class="mt-5" :show-title="false">
        <HotWordDetail :version-type="versionType" :phoenix-checker="phoenixChecker" :data="bwPriceInfo.wordAskWords" />
      </BaseContainer>
      <BaseContainer class="mt-5" :show-title="false">
        <BwBaidu
          :coordinates-hook="coordinatesHook"
          :price-utils="proPriceUtils"
          :mobile-sold="mobileSold"
          :pc-sold="pcSold"
          :pc-disable="pcDisable"
          :mobile-disable="mobileDisable"
          v-model:creative-select="creativeSelect"
          v-model:qihu360-select="qihu360Select"
        />
        <BwPremium :premiums="premiums" />
      </BaseContainer>
    </div>

    <div>
      <CbFooter
        v-show="CiBao || CBYXB"
        :submitting="submitting || bwSubmitting"
        :current-package="currentPackage"
        :selected-table-data="selectedTableData"
        :combo-price-id="CiBaoFormFields.comboPriceId"
        :combo-price-list="comboPriceList"
        @submit="handleSubmit"
      />
      <BwFooter
        v-show="(getResult && BW) || BWYXB"
        :btn-text="btnText"
        :total-price="proTotalPrice"
        @submit="handleBwSubmit"
      />
      <HJBWFooter
        v-show="HJBW"
        :submitting="submitting || bwSubmitting"
        :current-package="currentPackage"
        :selected-table-data="hjbwSelectedTableData"
        :marketPrice="marketPrice"
        :comboPrice="HJBWFormFields.comboPrice"
        @submit="handleHjbwSubmit"
      />
    </div>
  </base-container>
</template>

<script lang="ts" setup>
import { computed, defineOptions, onActivated, onDeactivated, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { compact, intersectionWith, isNil } from 'lodash-es'
import TableToolbar from '@/components/table-toolbar/index.vue'
import getKeywordList, { type CiBaoPriceAskParams } from '@/services/price-sheet/getKeywordList'
import getPackageList, { type PackageData } from '@/services/price-sheet/getPackageList'
import createPriceSheet from '@/services/price-sheet/createPriceSheet'
import { useMainStore } from '@/store/useMainStore'
import { usePriceSheetStore } from '@/store/usePriceSheetStore'
import type { VersionItem } from '@/views/price-sheet/interface'
import { BwComboPriceNameKeyMap, BwVersionTypeKeyMap } from '@/views/price-sheet/interface'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import KeywordTable from '@/views/price-sheet/components/KeywordTable.vue'
import SelectedTable from '@/views/price-sheet/components/SelectedTable.vue'
import BaseContainer from '@/components/base-container/index.vue'
import CbFooter from '@/views/price-sheet/components/CbFooter.vue'
import HJBWFooter from '@/views/price-sheet/components/HJBWFooter.vue'
import BwFooter from '@/views/price-sheet/components/BwFooter.vue'
import HotWordDetail from '@/views/price-sheet/components/HotWordDetail.vue'
import ForbiddenText from '@/views/price-sheet/components/ForbiddenText.vue'
import BwBaidu from '@/views/price-sheet/components/BwBaidu.vue'
import QueryFields from '@/views/price-sheet/components/QueryFields.vue'
import type { BwPriceAskParams } from '@/services/price-sheet/getBwPriceAskWords'
import getBwPriceAskWords from '@/services/price-sheet/getBwPriceAskWords'
import { reactiveComputed } from '@vueuse/core'
import getComboPriceList from '@/services/price-sheet/getComboPriceList'
import Divider from '@/components/divider/index.vue'
import { useCategory } from '@/hooks/useCategotry'
import getPhoenixRegionCheckResult from '@/services/price-sheet/getPhoenixRegionCheckResult'
import { CreativePictureEnum, TypeEnum, VersionTypeEnum, LandingPageEnum, IsFromHjzwEnum } from '@/core/enums/type'
import { ProductEnum } from '@/core/enums/platform'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { PricePlatformKeyMap } from '@/core/mapper/platform'
import { ApproveStatusEnum } from '@/core/enums/status'
import type { VectorX } from '@/core/interfaces/priceTable'
import { DataIndex } from '@/core/enums/name'
import type { Coordinates } from '@/views/price-sheet/hooks/usePriceCoordinates'
import { usePriceCoordinates } from '@/views/price-sheet/hooks/usePriceCoordinates'
import { usePriceTable } from '@/views/price-sheet/hooks/usePriceTable'
import { useTotalPrice } from '@/views/price-sheet/hooks/useTotalPrice'
import { usePriceSold } from '@/views/price-sheet/hooks/usePriceSold'
import BwPremium from '@/views/price-sheet/components/BwPremium.vue'
import is from '@/utils/is'
import { fromZodError } from 'zod-validation-error'
import { bwPriceDataNormalizer, bwPriceDataParser } from '@/core/parser/priceDataParser'
import { useReloadModal } from '@/hooks/useReloadModal'
import { usePriceDisable } from '@/views/price-sheet/hooks/usePriceDisable'
import { add, toFixed } from '@/utils/math'
import createBwPriceSheet from '@/services/price-sheet/createBwPriceSheet'
import QueryFieldsHJBW from '@/views/price-sheet/components/QueryFieldsHJBW.vue'
import { toLabelValue } from '@/utils'
import { LandingPageMap } from '@/core/mapper/type'
import getKeywordListHjbw from '@/services/price-sheet/getKeywordListHjbw'
import type { HjbwPriceAskParams } from '@/services/price-sheet/getKeywordListHjbw'
import { byteLength } from '@/utils'
import createHjbwPriceSheet from '@/services/price-sheet/createHjbwPriceSheet'
import { ComboPriceNameEnum } from '@/core/enums/name'
import { useRoute } from 'vue-router'
const route = useRoute()
const packageCode = ref(1)
const LandingPageList = computed(() => {
  return hjbwSelectedTableData.value?.length < 5
    ? toLabelValue(LandingPageMap).filter((item) => item.value !== 2)
    : toLabelValue(LandingPageMap)
})
const shuzi = ref(5)

defineOptions({
  name: 'PricePackage'
})

useReloadModal()
const router = useRouter()
const mainStore = useMainStore()
const priceSheetStore = usePriceSheetStore()

const loading = computed(() => {
  return keywordLoading.value || hjbwKeywordLoading.value
})
const [, createHjbwPriceSheetFn] = createHjbwPriceSheet()
const [packageList, fetchPackageList] = getPackageList()
const [rawKeywordTableData, fetchKeywordList, keywordLoading] = getKeywordList()
const [rawKeywordTableDataHjbw, getKeywordListHjbwFn, hjbwKeywordLoading] = getKeywordListHjbw()
const [, fetchPriceSheet, submitting] = createPriceSheet()
const [, fetchBwPriceSheet, bwSubmitting] = createBwPriceSheet()
const [bwPriceInfo, fetchBwPriceAskWord] = getBwPriceAskWords()
const [comboPriceList, fetchComboPriceList, comboPriceLoading] = getComboPriceList()
const [phoenixChecker, fetchPhoenixRegionChecker] = getPhoenixRegionCheckResult()

const versionList = ref<VersionItem[]>([
  {
    title: '标准版',
    desc: '店铺显示商户电话，商户可根据需求自定义电话号码',
    active: true,
    id: VersionTypeEnum.Normal
  },
  {
    title: '普惠版',
    desc: '店铺不显示商户电话，平台400电话转接商户电话',
    active: false,
    id: VersionTypeEnum.Cheap
  },
  {
    title: '高级版',
    desc: '店铺显示商户电话，商户自定义店铺域名',
    active: false,
    id: VersionTypeEnum.Pro
  }
])

const defaultBwFormFields: () => BwPriceAskParams = () => ({
  biaowang: ProductEnum.BW,
  priceAskWords: [],
  serviceAreas: [],
  userAreas: [],
  assessmentPricesId: 0
})

const defaultCibaoFormFields: () => CiBaoPriceAskParams = () => ({
  cibao: ProductEnum.CiBao,
  packageId: undefined,
  comboPriceId: undefined,
  keyword: '',
  zzbwOrderNo: ''
})

const defaultHJBWFormFields: () => HjbwPriceAskParams = () => ({
  cibao: ProductEnum.HJBW,
  packageId: undefined,
  comboPriceId: undefined,
  comboPriceName: ComboPriceNameEnum.YEAR,
  keyword: undefined,
  onLinePeriod: '7*24',
  shopType: LandingPageEnum.SinglePage,
  comboPrice: undefined,
  hzTransferCode: IsFromHjzwEnum.Yes,
  hzNotes: undefined
})
const marketPrice = ref<number>()

const bwSearching = ref(false)
const getResult = ref(false)
const isActivated = ref(false)
const creativeSelect = ref(false)
const qihu360Select = ref(false)
const QueryFieldsRef = ref<InstanceType<typeof QueryFields>>()
const releaseRange = `${dayjs().add(10, 'day').format('YYYY-MM-DD')}`
const selectedTableData = ref<PriceKeyword[]>([])
const keywordTableData = ref<PriceKeyword[]>([])
const hjbwSelectedTableData = ref<PriceKeyword[]>([])
const hjbwKeywordTableData = ref<PriceKeyword[]>([])
const BwFormFields = ref<BwPriceAskParams>(defaultBwFormFields())
const CiBaoFormFields = ref<CiBaoPriceAskParams>(defaultCibaoFormFields())
const HJBWFormFields = ref<HjbwPriceAskParams>(defaultHJBWFormFields())
const type = ref<ProductEnum>(5)
// watch(
//   () => code.value,
//   (val) => {
//     console.log(val, 'watch')
//     if (val === TypeCode.BW) {
//       type.value = ProductEnum.BW
//     } else if (val === TypeCode.HJ) {
//       type.value = ProductEnum.HJBW
//     }
//     else if (val === TypeCode.BWYXB) {
//       type.value = ProductEnum.BWYXB
//     }
//     else if (val === TypeCode.CB) {
//       type.value = ProductEnum.CiBao
//     }
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )

const { BW, BWYXB, CiBao, CBYXB, HJBW } = useCategory(type)

const queryFields = reactiveComputed(() => {
  return BW.value || BWYXB.value
    ? BwFormFields.value
    : CiBao.value || CBYXB.value
      ? CiBaoFormFields.value
      : HJBWFormFields.value
})
const versionType = computed(() => {
  return versionList.value.find((v) => v.active)?.id ?? VersionTypeEnum.Normal
})
const assessmentPrices = computed(() => {
  return bwPriceInfo.assessmentPrices
})
const premiums = computed(() => {
  return bwPriceInfo.premiums || []
})
const premiumRatio = computed(() => {
  return premiums.value.reduce((a, b) => {
    return add(a, b.premiumRatio).toNumber()
  }, 1)
})
const comboPriceData = computed(() => {
  return comboPriceList.value.find((c) => c.id === CiBaoFormFields.value.comboPriceId)
})
const hasCreativePicture = computed(() => {
  return creativeSelect.value ? CreativePictureEnum.yes : CreativePictureEnum.no
})

const coordinatesHook = usePriceCoordinates()
const priceUtils = usePriceTable(coordinatesHook, assessmentPrices)
const totalPrice = useTotalPrice(
  priceUtils.currentBaiduPrice,
  priceUtils.current360Price,
  priceUtils.creativePrice,
  creativeSelect,
  qihu360Select
)
const { mobileDisable, pcDisable } = usePriceDisable(bwPriceInfo)
const { mobileSold, pcSold } = usePriceSold(bwPriceInfo, versionType, phoenixChecker, BwFormFields)
const { currentBaiduPriceData, current360PriceData } = priceUtils
const { resetCoordinates, setBaiduCoordinates, set360Coordinates } = coordinatesHook

const proPriceUtils = usePriceTable(coordinatesHook, assessmentPrices, premiums)
const proTotalPrice = useTotalPrice(
  proPriceUtils.currentBaiduPrice,
  proPriceUtils.current360Price,
  proPriceUtils.creativePrice,
  creativeSelect,
  qihu360Select
)

function defaultCoordinates(): Coordinates {
  if (mobileSold.value && pcSold.value) {
    return []
  }

  if (pcDisable.value && mobileDisable.value) {
    return []
  }

  if (!pcSold.value && !mobileSold.value && !pcDisable.value && !mobileDisable.value) {
    return [0, DataIndex.Platform5x8]
  } else if (pcSold.value || pcDisable.value) {
    return [0, DataIndex.Mobile5x8]
  } else if (mobileSold.value || mobileDisable.value) {
    return [0, DataIndex.Pc5x8]
  } else {
    return []
  }
}

const btnText = computed(() => {
  if (bwPriceInfo.failtureCode) {
    return '提交审核'
  } else {
    return '提交审核'
  }
})

const currentPackage = computed<Partial<PackageData>>(() => {
  return packageList.value.find((p) => p.id === CiBaoFormFields.value.packageId) || {}
})

function resetVersionList() {
  versionList.value.forEach((v) => {
    v.active = false
  })
  versionList.value[0].active = true
}

async function handleBwSearcher() {
  getResult.value = false
  bwSearching.value = true
  bwDataReset()

  const [phoenixErr] = await fetchPhoenixRegionChecker({
    keywords: BwFormFields.value.priceAskWords
  })
  if (phoenixErr) {
    bwSearching.value = false
    return message.error(phoenixErr?.message, 5)
  }

  const [bwErr] = await fetchBwPriceAskWord(BwFormFields.value)
  if (bwErr) {
    bwSearching.value = false
    return message.error(bwErr?.message, 5)
  }
  bwSearching.value = false
  getResult.value = true

  if (bwPriceInfo.failtureCode) {
    message.warning(bwPriceInfo.msg, 5)
  } else {
    BwFormFields.value.assessmentPricesId = bwPriceInfo.assessmentPricesId
    message.success('关键词已审核通过，确认套餐后可以确认订单~')
  }

  // 这里设置坐标锁定标王百度的格子
  const coordinates = defaultCoordinates()
  setBaiduCoordinates(coordinates)
  set360Coordinates(coordinates)
}

async function loadKeywordList() {
  if (!currentPackage.value) {
    message.error('请先选择套餐')
    return
  }

  if ('cibao' in queryFields) {
    if (!queryFields.keyword) {
      message.error('请输入关键词')
      return
    }
    const [err] = await fetchKeywordList({
      keyword: queryFields.keyword,
      productId: 7
    })

    if (!err) {
      intersectionSelectedWord()
    }
  }
}

async function hjbwLoadKeywordList() {
  if (!HJBWFormFields.value.keyword) return message.warning('请输入需要查询的关键词！')
  const len = byteLength(HJBWFormFields.value.keyword)
  if (len < 8) return message.warning('关键词小于8个字节')

  const [err] = await getKeywordListHjbwFn({
    keyword: HJBWFormFields.value.keyword
  })
  if (!err) {
    HjbwIntersectionSelectedWord()
  }
}

function intersectionSelectedWord() {
  const result = intersectionWith(
    rawKeywordTableData.value,
    selectedTableData.value,
    (a, b) => a.frontKey === b.frontKey
  )

  result.forEach((item) => {
    item.selected = true
  })

  keywordTableData.value = rawKeywordTableData.value
}

function HjbwIntersectionSelectedWord() {
  const result = intersectionWith(
    rawKeywordTableDataHjbw.value,
    hjbwSelectedTableData.value,
    (a, b) => a.frontKey === b.frontKey
  )

  result.forEach((item) => {
    item.selected = true
  })

  hjbwKeywordTableData.value = rawKeywordTableDataHjbw.value
}

watch(
  () => hjbwSelectedTableData.value.length,
  (val) => {
    if (val < 5) {
      marketPrice.value = 3680 * val
      HJBWFormFields.value.comboPrice = 2800 * val
      HJBWFormFields.value.shopType = LandingPageEnum.SinglePage
    } else if (val === 5) {
      marketPrice.value = 16800
      HJBWFormFields.value.comboPrice = 12800
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val > 5 && val < 10) {
      marketPrice.value = Number(((16800 / 5) * val).toFixed(2))
      HJBWFormFields.value.comboPrice = Number(((12800 / 5) * val).toFixed(2))
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val === 10) {
      marketPrice.value = 29800
      HJBWFormFields.value.comboPrice = 23800
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    } else if (val > 10) {
      marketPrice.value = Number(((29800 / 10) * val).toFixed(2))
      HJBWFormFields.value.comboPrice = Number(((23800 / 10) * val).toFixed(2))
      HJBWFormFields.value.shopType = LandingPageEnum.Shop
    }
  }
)

function handleCiBaoReset() {
  CiBaoFormFields.value.keyword = ''
  selectedTableData.value = []
  keywordTableData.value = []
}

function handleHjbwReset() {
  HJBWFormFields.value.keyword = ''
  HJBWFormFields.value.shopType = LandingPageEnum.SinglePage
  hjbwSelectedTableData.value = []
  hjbwKeywordTableData.value = []
}

function handleBwReset() {
  getResult.value = false
  BwFormFields.value = defaultBwFormFields()
  QueryFieldsRef.value?.handleBwReset()
  bwDataReset()
}

function bwDataReset() {
  resetCoordinates()
  resetVersionList()
  creativeSelect.value = false
  qihu360Select.value = false
}

async function loadPackageList() {
  const [err] = await fetchPackageList()

  if (!err) {
    CiBaoFormFields.value.packageId = packageList.value[0]?.value

    if (CiBaoFormFields.value.packageId) {
      await handlePackageChange(CiBaoFormFields.value.packageId)
    }
  }
}

function handlePackageChange(comboId: number) {
  CiBaoFormFields.value.comboPriceId = undefined
  fetchComboPriceList({
    comboId
  })
}

async function handleSubmit() {
  // if (route.name != 'price-package-wb' || route.name != 'price-package-df') {
  //   if (isNil(CiBaoFormFields.value.comboPriceId)) {
  //     return message.error('请选择推广时长')
  //   }
  // }

  if (isNil(CiBaoFormFields.value.comboPriceId)) {
    return message.error('请选择推广时长')
  }

  // if (route.name != 'price-package-wb' || route.name != 'price-package-df') {
  //   if (isNil(CiBaoFormFields.value.comboPriceId)) {
  //     return message.error('请选择推广时长')
  //   }
  // }

  Modal.confirm({
    title: '提示',
    content: '确定提交审核吗？',
    async onOk() {
      const [err] = await fetchPriceSheet({
        comboPriceName: comboPriceData.value?.info!,
        comboPriceId: comboPriceData.value?.id ?? 0,
        comboPrice: comboPriceData.value?.premiumPrice ?? 0,
        premiumRatio: comboPriceData.value?.premiumRatio ?? 0,
        marketPrice: comboPriceData.value?.price ?? 0,
        comboName: currentPackage.value?.comboName!,
        zzbwOrderNo: currentPackage.value?.zzbwOrderNo!,
        comboId: currentPackage.value?.id!,
        proxyId: mainStore.userInfo!.proxy_id,
        proxyName: mainStore.userInfo!.proxy_name,
        priceAskWords: selectedTableData.value,
        sellerName: mainStore.userInfo!.full_name,
        sellerId: mainStore.userInfo!.id,
        productId: type.value,
        areas: '全国',
        type: TypeEnum.NEW,
        versionType: VersionTypeEnum.Normal,
        approveStatus: ApproveStatusEnum.PENDING,

        machineExamine: bwPriceInfo.machineExamine
      })

      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: selectedTableData.value,
          CibaoPriceData: {
            comboName: currentPackage.value.comboName!,
            comboPriceName: comboPriceData.value!.info
          },
          approveStatus: ApproveStatusEnum.PENDING,
          type: type.value
        })

        handleBwReset()
        handleCiBaoReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}

async function handleHjbwSubmit() {
  if (isNil(HJBWFormFields.value.areas)) {
    return message.warn('请选择推广地域！')
  }
  if (isNil(HJBWFormFields.value.shopType)) {
    return message.warn('落地页不能为空！')
  }
  if (HJBWFormFields.value.hzTransferCode === IsFromHjzwEnum.Yes && !HJBWFormFields.value.hzNotes) {
    return message.warn('请输入转移备注！')
  }

  Modal.confirm({
    title: '提示',
    content: '确定提交审核吗？',
    async onOk() {
      const [err] = await createHjbwPriceSheetFn({
        hzTransferCode: HJBWFormFields.value.hzTransferCode,
        hzNotes: HJBWFormFields.value.hzNotes,
        comboPriceName: HJBWFormFields.value.comboPriceName,
        comboPriceId: comboPriceData.value?.id ?? 0,
        comboPrice: comboPriceData.value?.premiumPrice ?? 0,
        premiumRatio: comboPriceData.value?.premiumRatio ?? 0,
        marketPrice: comboPriceData.value?.price ?? 0,
        proxyId: mainStore.userInfo!.proxy_id,
        proxyName: mainStore.userInfo!.proxy_name,
        priceAskWords: hjbwSelectedTableData.value,
        sellerName: mainStore.userInfo!.full_name,
        sellerId: mainStore.userInfo!.id,
        productId: ProductEnum.HJBW,
        areas: HJBWFormFields.value.areas?.join(',') || '',
        type: TypeEnum.NEW,
        versionType: VersionTypeEnum.Normal,
        approveStatus: ApproveStatusEnum.PENDING,
        onLinePeriod: HJBWFormFields.value.onLinePeriod,
        shopType: HJBWFormFields.value.shopType,

        machineExamine: 0
      })

      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: hjbwSelectedTableData.value,
          HjbwPriceData: {
            comboPriceName: HJBWFormFields.value.comboPriceName as unknown as ComboPriceNameEnum
          },
          approveStatus: ApproveStatusEnum.PENDING,
          type: ProductEnum.HJBW
        })

        handleBwReset()
        handleCiBaoReset()
        handleHjbwReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}

function getBwComboName() {
  return compact([
    currentBaiduPriceData.value.dataIndex && '百度标王',
    creativeSelect.value && '创意配图',
    qihu360Select.value && '360标王',
    BwVersionTypeKeyMap[versionType.value],
    '标准版钻石店铺',
    ...premiums.value.map((item) => {
      return item.premiumName
    })
  ]).join(' | ')
}

async function handleBwSubmit() {
  const normalizeData = bwPriceDataNormalizer(
    BwFormFields.value,
    bwPriceInfo,
    currentBaiduPriceData.value,
    current360PriceData.value,
    hasCreativePicture.value,
    getBwComboName(),
    versionType.value,
    qihu360Select.value,
    totalPrice.value,
    pcSold.value,
    mobileSold.value,
    premiumRatio.value,
    proTotalPrice.value
  )

  if (is.boolean(normalizeData)) return false

  const valid = bwPriceDataParser().safeParse(normalizeData)
  if (!valid.success) {
    return message.error(fromZodError(valid.error).message)
  }

  Modal.confirm({
    title: '提示',
    content: '确定提交吗？',
    async onOk() {
      const [err] = await fetchBwPriceSheet({
        ...normalizeData,
        machineExamine: bwPriceInfo.machineExamine || 0
      })

      if (!err) {
        priceSheetStore.setPurchaseData({
          selectedData: normalizeData.priceAskWords,
          approveStatus: normalizeData.approveStatus,
          BwPriceData: {
            quote: currentBaiduPriceData.value.quote as VectorX['quote'],
            comboPriceName: BwComboPriceNameKeyMap[currentBaiduPriceData.value.timer!],
            columnName: PricePlatformKeyMap[currentBaiduPriceData.value.columnName!],
            hasCreativePicture: hasCreativePicture.value,
            versionType: versionType.value
          },
          Bw360PriceData: qihu360Select.value
            ? {
                quote: current360PriceData.value.quote!,
                comboPriceName: BwComboPriceNameKeyMap[current360PriceData.value.timer!],
                columnName: PricePlatformKeyMap[current360PriceData.value.columnName!]
              }
            : undefined,
          type: type.value
        })

        handleBwReset()
        handleCiBaoReset()
        handleHjbwReset()

        router.replace({
          name: 'price-purchase'
        })
      }
    }
  })
}

onMounted(() => {
  loadPackageList()
})

onActivated(() => {
  isActivated.value = true
})

onDeactivated(() => {
  isActivated.value = false
})
</script>

<style scoped lang="scss">
.toolbar {
  width: 700px;

  &-keyword {
    max-width: 326px;
    min-width: 250px;
  }

  &-local {
    padding-top: 5px;
    padding-bottom: 5px;
  }
}

.search-icon {
  color: #a6a6a6;
}
</style>
